<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  

  <script type="text/javascript">
    var data = [
      {
        id: 1,
        pid: 2
      },
      {
        id: 2,
        pid: 0
      },
      {
        id: 3,
        pid: 4
      },
      {
        id: 4,
        pid: 0
      },
      {
        id: 5,
        pid: 4
      },
      {
        id: 6,
        pid: 1
      },
      {
        id: 7,
        pid: 6
      },
      {
        id: 8,
        pid: 2
      },
    ];



    function formatDataTree(data) {
      let parents = data.filter(p => p.pid === 0),
          children = data.filter(c => c.pid !== 0);
      
      dataToTree(parents, children);
      
      return(parents);

      function dataToTree(parents, children) {
        parents.map( p => {
          children.map( (c, i) => {
            if(c.pid === p.id) {
              let _children = JSON.parse(JSON.stringify(children));
              _children.splice(i, 1);
              dataToTree([c], _children);
              if(p.children) {
                p.children.push(c);
              } else {
                p.children = [c];
              }
            }
          });
        })
      }
    }

    function formatDataTree2(data) {
      const _data = JSON.parse(JSON.stringify(data));

      return _data.filter(p => {
        const _arr = _data.filter(c => c.pid === p.id);
        _arr.length && (p.children = _arr);

        return p.pid === 0;
      })
    }

    console.log(formatDataTree2(data))
  </script>
</body>
</html>